package com.wanxi.chat.repository.impl;


import com.mongodb.client.result.UpdateResult;
import com.wanxi.chat.mongo.api.MongoFeignClient;
import com.wanxi.chat.result.CommonResult;
import com.wanxi.chat.vo.ChatQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Component
public class ChatRepositoryImpl implements MongoFeignClient {
    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/add")
    @ResponseBody
    @Override
    public CommonResult mongoAddFeign(@RequestBody ChatQueryVO chatQueryVO) {
        chatQueryVO.setState("1");
        chatQueryVO.setLineState("0");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        chatQueryVO.setDate(simpleDateFormat.format(date));
        ChatQueryVO save = mongoTemplate.save(chatQueryVO);
        return   CommonResult.success(save);
    }

    @PostMapping("/update")
    @ResponseBody
    @Override
    public CommonResult mongoUpdateFeign(@RequestBody ChatQueryVO chatQueryVO) {
        Query query = new Query();
        query.addCriteria(Criteria.where("toId").is(chatQueryVO.getToId()).and("lineState").is("0"));
        final long count = mongoTemplate.count(query, ChatQueryVO.class);
        Update update=new Update();
        int updateCount= 0;
        for (int i = 0; i < count; i++) {
            update.set("lineState","1");
            mongoTemplate.upsert(query, update, ChatQueryVO.class);
            updateCount++;
        }
        return CommonResult.success(updateCount);
    }

    @PostMapping("/delete")
    @ResponseBody
    @Override
    public CommonResult mongoDeleteFeign(@RequestBody ChatQueryVO chatQueryVO) {
        Query query = new Query();
        query.addCriteria(Criteria.where("toId").is(chatQueryVO.getToId()));
        Update update=new Update();
        update.set("state","0");
        UpdateResult upsert = mongoTemplate.upsert(query, update, ChatQueryVO.class);
        return CommonResult.success(upsert);
    }

    @GetMapping("/findmessage")
    @ResponseBody
    @Override
    public CommonResult mongoFindFeign(@RequestBody ChatQueryVO chatQueryVO) {
        List<ChatQueryVO> toId = mongoTemplate.find(new Query(Criteria.where("toId").is(chatQueryVO.toId)), ChatQueryVO.class);
        return CommonResult.success(toId) ;
    }
}
